package main

import (
	"fmt"
	"iot-base/common/cache"
	"iot-base/common/config"
	"iot-base/common/logger"
	"iot-base/common/notify"
	"iot-base/common/propertytype"
	"iot-base/devc/common/loader"
	"math/rand"
	"strings"
	"sync"
	"time"
)

func init() {
	loader.SetParam(false, "magical", 30, eachDev)
}

func main() {
	logger.Log.Warn("--------------------magical-----------------begin-----on--------" + config.PType)

	wg := sync.WaitGroup{}
	wg.Add(1)
	wg.Wait()

}

var Rander = rand.New(rand.NewSource(time.Now().UnixNano()))

func randomData(pProp *cache.ItemInfo) interface{} {
	max := 100.0
	min := 0.0
	var target int64
	if pProp.HasRange {
		max = pProp.Max
		min = pProp.Min
	}
	target = int64((int(min) + Rander.Intn(int(max-min+1))))
	switch pProp.Type {
	case "int":
		return int64(target)
	case "float", "float32", "float64":
		var fftarget float64
		if max-min >= 1 {
			fftarget = min + float64(Rander.Intn(int(max-min))) + Rander.Float64()
		} else {
			fftarget = min + (max-min)*Rander.Float64()
		}
		if fftarget > 100 {
			return int64(fftarget)
		}
		if fftarget > 10 {
			return fmt.Sprintf("%.1f", fftarget)
		}
		return fmt.Sprintf("%.2f", fftarget)

	case "enum":
		if pProp.EnumList == nil {
			return 0
		}
		array := *pProp.EnumList
		len := len(array)
		if len > 0 {
			index := Rander.Intn(len)
			return array[index]
		}
		return 0
	case "bool":
		index := Rander.Intn(10) % 2
		if index == 0 {
			return true
		}
		return false
	case "text", "stream":
		return fmt.Sprintf("%v", target)
	}

	return nil

}
func structRandom(values []propertytype.StructValue, props []*cache.ItemInfo) {
	//values[i] = make([]propertytype.StructValue, len(props))
	for i, pProp := range props {
		values[i].SubID = pProp.SubID
		values[i].Value = randomData(pProp)
	}

}
func structArrayRandom(values [][]propertytype.StructValue, id string, pid string, props []*cache.ItemInfo) {

	for i := 0; i < 2; i++ {
		values[i] = make([]propertytype.StructValue, len(props))
		for j, pProp := range props {
			values[i][j].SubID = pProp.SubID
			values[i][j].Value = randomData(pProp)
		}
	}

}
func makeValue(pThing *cache.ThingInfo, pProp *cache.ItemInfo) {
	//thing, err := cache.GetThing(id)
	//if err == nil {
	//isExist, pProp := cache.GetModelProperty(thing.Thing.ModelID, pid, "")
	id := pThing.Thing.UID
	if pProp != nil {
		var pid = pProp.PID
		if pProp.Type == "array" {
			ok, props := cache.GetChildProperties(pThing.Thing.ModelID, pid)
			if ok {
				if len(props) == 1 {
					pArray := make([]interface{}, 2)
					pData := &propertytype.Value{
						TID:        id,
						PID:        pid,
						Value:      pArray,
						PickTime:   time.Now().Unix(),
						ReportTime: time.Now().Unix(),
					}
					for i := 0; i < 2; i++ {
						pArray[i] = randomData(props[0])
					}
					fmt.Println("---------******--------", pData)
					notify.RawDataEx(pData)

				} else {
					pArray := make([][]propertytype.StructValue, 2)
					pData := &propertytype.Value{
						TID:        id,
						PID:        pid,
						Value:      pArray,
						PickTime:   time.Now().Unix(),
						ReportTime: time.Now().Unix(),
					}
					structArrayRandom(pArray, id, pid, props)
					fmt.Println("---------******--------", pData)
					notify.RawDataEx(pData)

				}

			}

		}
		if pProp.Type == "struct" {
			ok, props := cache.GetChildProperties(pThing.Thing.ModelID, pid)
			if ok {
				pStruct := make([]propertytype.StructValue, len(props))
				pData := &propertytype.Value{
					TID:        id,
					PID:        pid,
					Value:      pStruct,
					PickTime:   time.Now().Unix(),
					ReportTime: time.Now().Unix(),
				}
				structRandom(pStruct, props)
				notify.RawDataEx(pData)
				fmt.Println("---------******--------", pData)
			} else {
				fmt.Println("GetChildProperties -------error")
			}
		} else {
			pData := &propertytype.Value{
				TID:        id,
				PID:        pid,
				SubID:      pProp.SubID,
				Value:      randomData(pProp),
				PickTime:   time.Now().Unix(),
				ReportTime: time.Now().Unix(),
			}
			notify.RawDataEx(pData)
		}

	} else {
		fmt.Println("get property -------error")
	}

}

//设备增加的回调
func eachDev(id string, thing *cache.ThingInfo, dev interface{}, num int64) (interface{}, error) {
	fmt.Println("------------begin----------------")
	mid := thing.Thing.ModelID
	props, err := cache.GetModelElements(mid, "property")
	if err == nil {
		for _, pn := range props {
			//index := strings.LastIndex(pn,".")
			names := strings.Split(pn, ".")
			if len(names) <= 1 {
				ok, pro := cache.GetModelProperty(mid, pn, "")
				if ok {
					makeValue(thing, pro)
				}
			} else {
				for i := range names {
					if i > 0 {
						pid := strings.Join(names[0:i], ".")
						subid := strings.Join(names[i:], ".")
						ok, pro := cache.GetModelProperty(mid, pid, subid)
						if ok {
							makeValue(thing, pro)
						}
					}

				}
			}

		}
	}
	return nil, nil
}
